package com.starblink.login.forgotpassword.inputemail.ui

import com.alibaba.android.arouter.facade.annotation.Route
import com.starblink.android.basic.base.activity.BaseTVMActivity
import com.starblink.android.basic.ext.click
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.navigationTo
import com.starblink.android.basic.user.login.LoginManager
import com.starblink.basic.route.RoutePage
import com.starblink.basic.util.CommUtils
import com.starblink.login.databinding.ActivityForgotPswInputEmailBinding

/**
 * 忘记密码-输入邮箱
 */
@Route(path = RoutePage.Login.FORGOT_PSW_INPUT_EMAIL)
class ForgotPswInputEmailActivity :
    BaseTVMActivity<ActivityForgotPswInputEmailBinding, ForgotPswInputEmailVM>() {
    override fun initViewBinding(): ActivityForgotPswInputEmailBinding =
        ActivityForgotPswInputEmailBinding.inflate(layoutInflater)

    override fun initView() {
        super.initView()
        viewBinding.etEmailOrUsername.setOnEditInputListener {
            viewBinding.tvErrorHint.visibleOrGone(false)
            viewBinding.btnContinue.isEnabled = it.isNotEmpty()
        }

        viewBinding.btnContinue.isEnabled = viewBinding.etEmailOrUsername.text.isNotEmpty()
        viewBinding.btnContinue.click {
            val res = LoginManager.validateUserNameOrEmail(viewBinding.etEmailOrUsername.text)
            if (res == null) {
                // 输入的邮箱或用户名OK，接口验证
                var email: String? = null
                var userName: String? = null
                if (LoginManager.validateEmail(viewBinding.etEmailOrUsername.text) == null) {
                    email = viewBinding.etEmailOrUsername.text
                } else {
                    userName = viewBinding.etEmailOrUsername.text
                }
                viewModel.checkAccountExist(email, userName)
            } else {
                viewBinding.tvErrorHint.visibleOrGone(true)
                viewBinding.tvErrorHint.text = res
            }
        }
    }

    override fun initObservable() {
        super.initObservable()
        viewModel.checkResultLiveData.observe(this) {
            if (it.first == true) {
                // it==true，账号已存在,可以发送邮件
                navigationTo(RoutePage.Login.FORGOT_PSW_EMAIL_SENT) {
                    withString(LoginManager.KEY_EMAIL, it.second)
                    withString(LoginManager.KEY_USERNAME, it.third)
                }
            } else {
                // 账户不存在
                viewBinding.tvErrorHint.visibleOrGone(true)
                viewBinding.tvErrorHint.text =
                    CommUtils.getString(com.starblink.basic.style.R.string.username_email_not_exist)
            }
        }
    }
}